package com.example.day01.controller;

import com.example.day01.pojo.User;
import com.example.day01.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class IndexController {
    @Autowired
    private UserService userService;
    @RequestMapping("/save")
    public String add(){
        return "save";
    }
    @RequestMapping("update")
    public String update(){
        return "update";
    }
    @PostMapping("/updateuser")
    public String updateuser(ModelMap map, @RequestParam int id,@RequestParam String name,@RequestParam String password) {
        User user = new User();
        user.setId(id);
        user.setName(name);
        user.setPassword(password);
        System.out.println(user);
        int flag = userService.update(user);
        map.put("flag", flag);
        System.out.println("flag="+flag);
        return "redirect:/";
    }
    @PostMapping("/saveuser")
    public String save(ModelMap map, @RequestParam int id,@RequestParam String name,@RequestParam String password) {
        User user = new User();
        user.setId(id);
        user.setName(name);
        user.setPassword(password);
        System.out.println(user);
        int flag = userService.save(user);
        map.put("flag", flag);
        System.out.println("flag="+flag);
        return "redirect:/";
    }
    @RequestMapping("/")
    public String index(Model model){
        List<User> users = userService.findAllUser();
        System.out.println(users);
        model.addAttribute("users",users);
        return "index";
    }
    @GetMapping("/delete/{id}")
    public String delete(ModelMap modelMap,@PathVariable("id") int id){
        System.out.println(id);
        int flag = userService.deleteUser(id);
        modelMap.put("flag",flag);
        System.out.println(flag);
        return "redirect:/";
    }

}
